import { getAppLatestVersion } from '@/api/common';
import userCommon from '@/store/common';

export async function APPUpdate() {
  const commonStore = userCommon();
  let installPlatform = 7;
  switch (commonStore.systemInfo.deviceBrand) {
    case 'huawei':
      installPlatform = 1;
      break;
    case 'apple':
      installPlatform = 2;
      break;
    case 'xiaomi':
      installPlatform = 3;
      break;
    case 'oppo':
      installPlatform = 4;
      break;
    case 'vivo':
      installPlatform = 5;
      break;
    default:
      installPlatform = 7;
      break;
  }
  try {
    const res = await getAppLatestVersion({
      appId: commonStore.systemInfo.appId,
      installPlatform: installPlatform
    });
    handleUpdate(res.data, commonStore.systemInfo);
  } catch (e) {
    //TODO handle the exception
  }

  uni.setStorage({
    key: 'device',
    data: deviceInfo
  });
}

// 判断是否需要更新
function handleUpdate(res, deviceInfo) {
  const commonStore = userCommon();
  if (res.version > deviceInfo.appVersionCode && res.versionName != deviceInfo.appVersion) {
    // 有更新
    commonStore.setRenew(true, res);
  } else {
    // 无更新
    commonStore.setRenew(false, null);
  }
}
